package com.aliyun.heiyu.powermaster.server.agent;

import com.aliyun.heiyu.common.util.LogUtils;
import io.grpc.stub.StreamObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

import com.aliyun.heiyu.powermaster.proto.PowerCommand;

public class Agent {
    private static Logger log = LoggerFactory.getLogger(Agent.class);

    private String id;
    private StreamObserver<PowerCommand> responseObserver;
    private boolean available;

    private int  maxPower;
    private long maxFreq;

    private int  power;
    private long freq;

    private int price;

    public Agent(String id, int maxPower, long maxFreq) {
        this.id = id;
        this.available = true;
        this.maxPower = maxPower;
        this.maxFreq = maxFreq;
    }

    public String getId() {
        return id;
    }

    public boolean available() {
        return available;
    }

    public void setAvailable(boolean avail) {
        this.available = avail;
    }

    public int getMaxPower() {
        return maxPower;
    }

    public long getMaxFreq() {
        return maxFreq;
    }

    public int getPower() {
        return power;
    }

    public long getFreq() {
        return freq;
    }

    public boolean hasLabel(String label) {
        if (label == "") {
            return true;
        }
        return false;
    }

    public void subscribe(StreamObserver<PowerCommand> responseObserver) {
        this.responseObserver = responseObserver;
    }

    public void update(int power, long freq) {
        this.power = power;
        this.freq  = freq;
    }

    public int getPrice() {
        return maxPower - power;
    }

    public void label(List<String> labels) {
        // TODO: labels
    }

    public void cap(int power, long freq) {
        PowerCommand cmd = PowerCommand.newBuilder()
                      .setCode(PowerCommand.Code.CAPPING)
                      .setPower(power).setFreq(freq).build();

        command(cmd);
    }

    public void hibernate() {
    }

    private void command(PowerCommand command) {
        if (responseObserver != null) {
            log.info("send command {} to agent {}", command.getCode(), LogUtils.vaildlog(id));
            responseObserver.onNext(command);
        }
    }
}

